<template>

  <div class="todos">
    <a-row type="flex" justify="space-around" align="middle">
      <a-col>
        <a-card title="备忘录" style="width: 800px">
          <template #extra>
            <a-space>
              <a @click.prevent="add">添加</a>
              <a @click="copy(state)">复制</a>
              <a @click="openModal">导入</a>
            </a-space>
          </template>
          <a-space>
            <a-progress type="circle" :width="50" :percent="percent" />
            <a-date-picker v-model:value="date" format="YYYY-MM-DD" />
          </a-space>
          <a-tabs v-model:activeKey="activeKey" type="card">
            <a-tab-pane v-for="(item, idx) in tabs" :key="idx" :tab="item">
              <draggable v-model="list" item-key="id" group="list" animation="500" filter=".holdings" @dragend="dragend">
                <template #item="{ element, index }">
                  <div>
                      <div v-if="idx === 0 && !element.isFinish && !element.isDelete" class="item" style="margin-top: 10px; background-color: #F0F0F0;padding: 5px;">
                        <a-space v-if="element.canEdit">
                          <clock-circle-two-tone />
                          <a-input class="holdings" v-if="element.canEdit" v-model:value="element.value" style="width: 350px" :placeholder="element.placeholder" @click="focus" />
                          <a-button type="primary" @click="sure(index)">确定</a-button>
                          <a-button @click="cancel(index)">取消</a-button>
                        </a-space>
                        <a-space v-else>
                          <clock-circle-two-tone />
                          <span style="display: inline-block; width: 350px">{{element.value}}</span>
                          <a-button @click="edit(index)">编辑</a-button>
                          <a-button danger @click="del(index)">删除</a-button>
                          <a-button type="primary" @click="finish(index)">已完成</a-button>
                        </a-space>
                      </div>
                      <div v-if="idx === 1 && element.isFinish && !element.isDelete" class="item" style="margin-top: 10px; background-color: #F0F0F0;padding: 5px;">
                        <a-space v-if="element.canEdit">
                          <check-circle-two-tone two-tone-color="#52c41a"/>
                          <a-input class="holdings" v-if="element.canEdit" v-model:value="element.value" style="width: 350px" :placeholder="element.placeholder" @click="focus" />
                          <a-button type="primary" @click="sure(index)">确定</a-button>
                          <a-button @click="cancel(index)">取消</a-button>
                        </a-space>
                        <a-space v-else>
                          <check-circle-two-tone two-tone-color="#52c41a"/>
                          <span style="display: inline-block; width: 350px">{{element.value}}</span>
                          <a-button @click="edit(index)">编辑</a-button>
                          <a-button danger @click="del(index)">删除</a-button>
                          <a-button @click="finish(index)">未完成</a-button>
                        </a-space>
                      </div>
                      <div v-if="idx === 2 && element.isDelete" class="item" style="margin-top: 10px; background-color: #F0F0F0;padding: 5px;">
                        <a-space>
                          <close-circle-two-tone two-tone-color="#cc0033" />
                          <span style="display: inline-block; width: 350px">{{element.value}}</span>
                          <a-button @click="del(index)">撤销</a-button>
                        </a-space>
                      </div>
                  </div>
                </template>
              </draggable>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>
    </a-row>
    <a-modal
      v-model:visible="visible"
      title="请粘贴你剪贴板的内容"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-textarea v-model:value="textVal" placeholder="请输入" :autoSize="{ minRows: 12, maxRows: 20 }"></a-textarea>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { message, Modal } from 'ant-design-vue'
import dayjs, { Dayjs } from 'dayjs';
import draggable from 'vuedraggable'
import { CheckCircleTwoTone, ClockCircleTwoTone, CloseCircleTwoTone } from '@ant-design/icons-vue';
import { reactive, ref, toRefs, computed, watch } from 'vue'
import useClipboard from 'vue-clipboard3';

const dragend = () => {
  localStorage.setItem('Todos', JSON.stringify(state))
}

const local = JSON.parse(localStorage.getItem('Todos')) || {
  list: [],
  oldVal: [],
  percent: 0,
  timestamp: 0
}


const state = reactive(local)

function add(idx) {
  const flag = state.list.length === 0 || (state.list.length > 0 && !!state.oldVal[state.list.length - 1])
  if(flag) {
    state.list.push({
      id: state.list.length + 1,
      value: '',
      placeholder: '请输入代办',
      canEdit: true,
      isFinish: false,
      isDelete: false
    })
  } else {
    if(!state.oldVal[state.list.length - 1]) {
      message.warning('请确认已输入代办')
      return
    }
    message.warning('请输入代办')
  }
  
}

function cancel(idx) {
  const flag = !state.oldVal[idx]
  if(flag) {
    state.list.splice(idx, 1)
  } else {
    state.list[idx].value = state.oldVal[idx]
    state.list[idx].canEdit = false
  }
}
function sure(idx) {
  const flag = state.list.length > 0 && !!state.list[state.list.length - 1].value
  if(flag) {
    state.list[idx].canEdit = false
    state.oldVal[idx] = state.list[idx].value
  } else {
    message.warning('请输入代办')
  }
}

function edit(idx) {
  state.list[idx].canEdit = true
  state.oldVal[idx] = state.list[idx].value || ''
}

function finish(idx) {
  state.list[idx].isFinish = !state.list[idx].isFinish
}

function del(idx) {
  Modal.confirm({
    title: '确定要操作吗？',
    okText: "提交",
    cancelText: "取消",
    onOk() {
      state.list[idx].isDelete = !state.list[idx].isDelete
    },
    onCancel() {
    }
  });
}

function focus(e) {
  e.srcElement.focus()
}

const { list, percent } = toRefs(state)

watch(state.list, (newVal) => {
  const length = newVal.length
  const finishLen = newVal.filter(item => item.isFinish).length
  state.percent = Math.floor((finishLen / length) * 100) 
  localStorage.setItem('Todos', JSON.stringify(state))
}, { deep: true, immediate: true })

const date = ref(dayjs(local.timestamp || dayjs(new Date())))

watch(date, (newVal) => {
  state.timestamp = dayjs(newVal).valueOf()
  localStorage.setItem('Todos', JSON.stringify(state))
})

const { toClipboard } = useClipboard();

const copy = async (value) => {
  try {
    await toClipboard(JSON.stringify(value));
    message.success('复制成功！');
  } catch (e) {
    message.error('复制失败！');
  }
};

const visible = ref<boolean>(false)
const textVal = ref<string>('')
const openModal = () => {
  visible.value = true
  textVal.value = ''
}

const handleOk = () => {
  visible.value = false
  try {
    const { list, percent, oldVal, timestamp } = JSON.parse(textVal.value)
    if(!list || !percent || !oldVal || !timestamp) {
      message.error('粘贴格式不正确！')
      return 
    }
    state.list = list
    state.oldVal = oldVal
    state.percent = percent
    state.timestamp = timestamp
    textVal.value = ''
  } catch(e) {
    message.error('粘贴格式不正确！')
  }
}

const handleCancel = () => {
  visible.value = false
  textVal.value = ''
}

const tabs = ref(['未完成', '已完成', '已删除'])
const activeKey = ref(0)

</script>

<style scoped>
</style>